import json
import httpx
from typing import Any
import os
from dotenv import load_dotenv
load_dotenv()
# 汽车入厂API配置
CAR_ENTER = os.getenv("BASEA_CAR_URL", "") + "/prl-Vehicle/web/vEnterRecordVehicle/queryPage?"
CAR_COOKIE = os.getenv("FUEL_TOKEN", "")

async def fetch_car_enter(startTime: str, endTime: str) -> dict[str, Any] | None:
    payload = {
        "beginInTime": startTime,
        "endInTime": endTime,
        "current": 1,
        "pageSize": 1000000000
    }
    headers = {
        "Content-Type": "application/json"
    }
    async with httpx.AsyncClient() as client:
        try:
            client.cookies.set('jreapSid', CAR_COOKIE)
            response = await client.post(CAR_ENTER, json=payload, headers=headers, timeout=30.0)
            response.raise_for_status()
            return response.json()
        except httpx.HTTPStatusError as e:
            return {"error": f"HTTP 错误: {e.response.status_code}"}
        except Exception as e:
            return {"error": f"请求失败: {str(e)}"}

def format_car_enter(data: dict[str, Any] | Any) -> str:
    if isinstance(data, str):
        try:
            data = json.loads(data)
        except Exception as e:
            return f"无法解析汽车入厂数据: {e}"
    if data.get("flag") == "error":
        return f"⚠️ {data['msg']}"
    resultList = data.get("result", {}).get("content", [])
    count = data.get("result", {}).get("totalElements")
    car_info = []
    if len(resultList) > 50:
        return "汽车入厂数量: {count}\n,查询结果超过50条，请缩小查询范围"
    for item in resultList:
        vehicle_no = item.get("vehicleNo", "未知")
        serial_no = item.get("serialNo", "未知")
        in_time = item.get("inTime", "未知")
        if in_time != "未知":
            in_time = in_time.split(" ")[0]
        ticket_weight = item.get("ticketWeight", "未知")
        car_info.append(f"{in_time}的入厂日期的车牌号{vehicle_no}")
    car_info_str = "；".join(car_info)
    return (
        f"{car_info_str}"
    )